package com.geeaks;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.concurrent.ExecutionException;
import org.apache.commons.io.IOUtils;
import cn.hutool.core.util.StrUtil;

public class App {
	
	private static String basePath = "D:"+File.separator+"Temp"+File.separator;
	
	public static void main(String[] args) throws ExecutionException, InterruptedException, IOException {
		try (Scanner sc = new Scanner(System.in)) {
			System.out.print("请选择下载类型（1.歌单id 2.歌曲id）：");
			String temp = sc.nextLine();
			List<Map<String, Object>> playlist = new ArrayList<Map<String, Object>>();
			String ids;
			if ("1".equals(temp)) {
				System.out.print("请输入歌单id（仅限单id）：");
				String playId = sc.nextLine();
				ids = API.playlist_detail(playId, playlist);
			} else if ("2".equals(temp)) {
				System.out.print("请输入歌曲id（支持多个id用','隔开）：");
				String songIds = sc.nextLine();
				ids = API.song_detail(songIds, playlist);
			} else {
				System.out.println("请输入正确类型");
				return;
			}
			playlist = API.song_url(ids, playlist);
			System.out.println("解析完成，共下载" + playlist.size() + "首歌曲");
			if (!Util.createDir("music163")) {
				System.err.println("创建文件夹失败，退出下载");
				return;
			}
			String playlistName = API.playListName;
			String path = basePath+StrUtil.replace(playlistName, "\"", "")+File.separator;
			File file = new File(path);
			if(!file.exists()) {
				file.mkdirs();
			}
			for (Map<String, Object> map : playlist) {
				if (map.get("url") != null) {
					String name = Util.formatFilePath(map.get("name").toString());
					File target = new File(path+ StrUtil.replace(name, "\"", "") + ".mp3");
					try {
						if(target.exists()) {
							System.err.println(name+"已存在，跳过");
							continue;
						}
						FileOutputStream outputStream = new FileOutputStream(target);
						IOUtils.write(Util.fileDownload(map.get("url").toString()), outputStream);
						System.out.println("已下载歌曲：" + Util.formatFilePath(map.get("name").toString()));
					} catch (IOException e) {
						e.printStackTrace();
						System.out.println("无法创建歌曲文件：" + map.get("name"));
					}
				} else {
					System.out.println("无法获取下载地址：" + map.get("name"));
				}
			}
		}
		System.exit(0);
	}
}
